const BaseMonitor = require('./base-monitor');

class BarometricPressureMonitor extends BaseMonitor {
  constructor(deviceId, mqttConnector) {
    super(deviceId, mqttConnector);
    this.topic = 'device/barometric-pressure';
    this.pressure = '0';
    this.unit = 'hPa';
    this.status = 'normal';

    // 注册消息处理
    this.onMessage(this.topic, this.handlePressureMessage.bind(this));
  }

  // 初始化
  async init() {
    await this.subscribe(this.topic);
    console.log('大气压传感器监控模块已初始化');
  }

  // 处理大气压消息
  handlePressureMessage(message) {
    try {
      // 只处理JSON格式消息（已在mqtt-connector中解析）
      if (typeof message === 'object' && message.type === 'sensor-data' && message.data) {
        this.pressure = message.data.value;
        this.unit = message.data.unit || 'hPa';
        this.status = message.data.status || 'normal';

        // 格式化大气压值为2位小数，并添加时间戳
        const formattedPressure = this.pressure;
        const timestamp = new Date(message.timestamp).toLocaleString();
        console.log(`[大气压传感器] 时间: ${timestamp}, 设备ID: ${message.deviceId}, 当前气压: ${formattedPressure}${this.unit}, 状态: ${this.status}`);

        // 触发数据更新事件（如果有监听器）
        if (this.onUpdate) {
          this.onUpdate({
            deviceId: message.deviceId,
            timestamp: message.timestamp,
            value: this.pressure,
            unit: this.unit,
            status: this.status
          });
        }
      } else {
        console.log(`无效的大气压消息格式: ${JSON.stringify(message)}`);
      }
    } catch (error) {
      console.error(`处理大气压消息错误: ${error.message}`);
    }
  }

  // 获取当前大气压数据
  async getCurrentData() {
    return {
      deviceId: this.deviceId,
      value: this.pressure,
      unit: this.unit,
      status: this.status,
      timestamp: Date.now()
    };
  }
}

module.exports = BarometricPressureMonitor;